from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 配置 ==========
GENDERS = ['男', '女']
BLOOD_TYPES = ['A', 'B', 'AB', 'O']
MARITAL_STATUS = ['未婚', '已婚', '离异', '丧偶']
EDUCATIONS = ['小学', '初中', '高中', '大专', '本科', '硕士', '博士']
OCCUPATIONS = ['教师', '医生', '工人', '学生', '公务员', '企业职员']
VISIT_TYPES = ['门诊', '住院', '急诊']
HOSPITALS = [
    {'code': 'HOSP001', 'name': '协和医院'},
    {'code': 'HOSP002', 'name': '华西医院'},
    {'code': 'HOSP003', 'name': '第一人民医院'},
    {'code': 'HOSP004', 'name': '省肿瘤医院'}
]

# ========== 生成函数 ==========
def generate_b02_1_records(num_records=50):
    sql_statements = []

    for i in range(num_records):
        hospital = random.choice(HOSPITALS)
        gender = random.choice(GENDERS)
        birth_date = fake.date_of_birth(minimum_age=0, maximum_age=90)
        patient_id = f"PT{1000+i}"
        patient_id_old = f"PAT_OLD{1000+i}"
        visit_sn = f"VIS{10000+i}"

        admission_datetime = datetime.now() - timedelta(days=random.randint(0, 365))
        discharge_datetime = admission_datetime + timedelta(days=random.randint(1, 15))

        data = {
            'abo_blood_type': random.choice(BLOOD_TYPES),
            'admission_datetime': admission_datetime.strftime('%Y-%m-%d %H:%M:%S'),
            'blood_type_s': random.choice(BLOOD_TYPES),
            'bolld_type_e': random.choice(BLOOD_TYPES),
            'certificate_no': fake.ssn(),
            'certificate_type': '身份证',
            'contact_person1': fake.name(),
            'contact_person2': fake.name(),
            'contact_phone_no1': fake.phone_number(),
            'contact_phone_no2': fake.phone_number(),
            'date_of_birth': birth_date.strftime('%Y-%m-%d'),
            'discharge_datetime': discharge_datetime.strftime('%Y-%m-%d %H:%M:%S'),
            'domicile_address': fake.address().replace("\n", ""),
            'domicile_city': fake.city(),
            'domicile_county': fake.city_suffix(),
            'domicile_province': fake.province(),
            'education': random.choice(EDUCATIONS),
            'education_code': str(random.randint(1,7)),
            'email': fake.email(),
            'ethnicity': '汉族',
            'from_table': None,
            'from_yy_record_id': fake.uuid4()[:8],
            'gender': gender,
            'health_card_no': f"HC{random.randint(10000,99999)}",
            'health_card_type': '医保卡',
            'height': str(random.randint(150, 190)),
            'home_address': fake.address().replace("\n", ""),
            'hospital_code': hospital['code'],
            'hospital_name': hospital['name'],
            'hospitalization_times': str(random.randint(1, 5)),
            'idcard_no': fake.ssn(),
            'inpatient_no': f"IP{10000+i}",
            'insurance_no': f"INS{10000+i}",
            'insurance_type': random.choice(['医保','自费','新农合']),
            'is_hospital_infected': random.choice(['是','否']),
            'marital_status': random.choice(MARITAL_STATUS),
            'marital_status_code': str(random.randint(1,4)),
            'medical_record_no': f"MR{10000+i}",
            'name': fake.name(),
            'nationality': '中国',
            'newbron_mark': random.choice(['是','否']),
            'occupation_code': str(random.randint(1,10)),
            'occupation_name': random.choice(OCCUPATIONS),
            'outpatient_no': f"OUT{10000+i}",
            'patient_gender': gender,
            'patient_id': patient_id,
            'patient_id_old': patient_id_old,
            'patient_identity': random.choice(['普通患者','医保患者']),
            'phone_no': fake.phone_number(),
            'phone_no2': fake.phone_number(),
            'record_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'record_status': 1,
            'record_update_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'rh_blood_type': random.choice(['阴','阳']),
            'visit_card_no': f"VC{10000+i}",
            'visit_datetime': admission_datetime.strftime('%Y-%m-%d %H:%M:%S'),
            'visit_doctor_name': fake.name(),
            'visit_doctor_no': f"DOC{100+i}",
            'visit_sn': visit_sn,
            'visit_status': random.choice(['在院','出院']),
            'visit_times': str(random.randint(1,5)),
            'visit_type': random.choice(VISIT_TYPES),
            'weight': str(random.randint(40,100)),
            'weixin': fake.user_name(),
            'yy_collection_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_record_md5': fake.md5(),
            'yy_upload_status': 0,
            'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_batch_time': datetime.now().strftime('%Y%m%d'),
            'yy_record_batch_id': f"BATCH{datetime.now().strftime('%Y%m%d')}_{i}"
        }

        sql = generate_sql('b02_1', data)
        sql_statements.append(sql)

    return sql_statements

# ========== 生成 SQL ==========
def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"

# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成 b02_1 患者就诊基本信息数据...")
    records = generate_b02_1_records(50)  # 生成50条测试数据
    MysqlUtils_AI.insert_data_to_hub(records, 'b02_1')
